package com.mcy.springbatch.reader;


import com.mcy.springbatch.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Component;

/**
 * 利用FlatFileItemReader从文件读取普通格式数据
 */
@Slf4j
@Component
public class ReadUserDataFlatFileItemReader extends FlatFileItemReader {

    public ReadUserDataFlatFileItemReader() {
        setResource(new FileSystemResource("/Users/calon/Desktop/userdata-1.txt"));
        setLineMapper(new DefaultLineMapper<SysUser>() {{
            setLineTokenizer(new DelimitedLineTokenizer("|") {{
                setNames(new String[] { "id","loginName","userName","idCard","phone","sex","address","email","status" });
                setComments(new String[] { "==","##" });
//                setLinesToSkip(1);//跳过第几行
            }});
            setFieldSetMapper(new BeanWrapperFieldSetMapper<SysUser>() {{
                setTargetType(SysUser.class);
            }});
            setSkippedLinesCallback(s -> log.error("skip line:"+s));

        }});
    }

    @Override
    protected Object doRead() throws Exception {
        log.info("读取数据，线程ID：{}",Thread.currentThread().getId());
        return super.doRead();
    }

}
